<?php
namespace app\shop\model;
use app\common\model\CommonModel;
use app\common\model\OrderActivity;
use app\common\model\OrderPayLog;
use app\common\model\OrderAfter;
use app\common\model\OrderGoods;
use app\common\model\Category;
use app\common\model\Order;
use app\common\model\Stock;
use think\Session;
use think\Db;

class OrderModel extends CommonModel
{
	/**
    * 获取订单列表
    */
    public static function getOrderList($info)
    {
        $where = self::is_where($info);
        $field = 'o.order_id,o.order_sn,o.addtime,o.username,o.phone,o.user_sn,o.clerk,o.order_money,o.stay_money';
        $orderList = (new Order())->gorderList($where,2,$field);
        
        $orderList->each(function($item, $key){
            $item->ogoods = (new OrderGoods())->orderGoodsList(['order_id'=>$item->order_id],2);
        });
        
        /*销售订单数*/
        $xsdd = self::order_count($where,'count');
        /*销售总额*/
        $xsze = self::order_count($where,'sum','o.order_money');
        /*待付款总额*/
        $dfk = self::order_count($where,'sum','o.stay_money');
        
        return [$orderList,$xsdd,$xsze,$dfk];
    }
    /**
    * 交易管理
    */
    public static function getOrderGoods($info)
    {
        $where['o.shop_id'] = Session::get('admin.shop_id');
        
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['o.addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['o.addtime'][] = ['<',strtotime($info['end'])];
			}
		}else{
            /*上月、当前月*/
            if(array_key_exists('shijian',$info))
            {
                if($info['shijian'] != '')
                {
                    if($info['shijian'] == CommonModel::NUMBER_ZERO)
                    {
                        $where['o.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                        $where['o.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
                    }else{
                        $where['o.addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                        $where['o.addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
                    }
                }
            }else{
                $where['o.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                $where['o.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
            }
        }
        $field = 'g.goods_id,g.goods_name,g.category_id,g.cat_id,g.brand_name,g.memory_name,g.attribute_name,g.colour_name,g.marker,g.selling_price,g.trade_price,g.unit';
        $orderList = (new Order())->gorderList($where,10,$field,'g.goods_id');
        $orderList->each(function($item, $key){
            $Category = new Category();
            $item->number = (new OrderGoods())->orderGoodsNumber(['goods_id'=>$item->goods_id,'is_show'=>0],'number');
            $item->category_id = $Category->getCategoryField(['category_id'=>$item->category_id],'category_name');
            $item->cat_id = $Category->getCategoryField(['category_id'=>$item->cat_id],'category_name');
        });
        return $orderList;
    }
    /**
    * 每日营业额
    */
    public static function turnover($info)
    {
        /*时间区间*/
        if((!isset($info['start']) || empty($info['start'])) && (!isset($info['end']) || empty($info['end'])))
		{
			$info['start'] = date('Y-m-d') . " 0:0:0";
            $info['end'] = date('Y-m-d') . " 23:59:59";
		}
        $Order = new Order();
        $where = self::is_where($info);
        $field = 'o.order_id,o.order_sn,o.addtime,o.username,o.phone,o.user_sn,o.clerk,o.order_money,o.stay_money';
        $orderList = $Order->gorderList($where,2,$field);
        $orderList->each(function($item, $key){
            $item->ogoods = (new OrderGoods())->orderGoodsList(['order_id'=>$item->order_id],2);
            $item->xjzf = self::payLogCount($item->order_id,0);
            $item->sjzf = self::payLogCount($item->order_id,1);
            $item->yhzf = self::payLogCount($item->order_id,2);
        });

        $ids = $Order->gordercolumn($where,'o.order_id');
        
        /*销售订单数*/
        $xsdd = self::order_count($where,'count');
        /*现金支付*/
        $xjzf = self::payLogCount($ids,0);
        /*手机支付*/
        $sjzf = self::payLogCount($ids,1);
        /*银行卡支付*/
        $yhzf = self::payLogCount($ids,2);
        /*销售总额*/
        $xsze = self::order_count($where,'sum','o.order_money');
        /*待付款总额*/
        $dfk = self::order_count($where,'sum','o.stay_money');
        
        return [$orderList,$xsdd,$xjzf,$sjzf,$yhzf,$xsze,$dfk];
    }
    /**
    * 条件整理
    */
	private function is_where($info)
	{
		$where['o.shop_id'] = Session::get('admin.shop_id');
        /*产品属性*/
		if($info['attribute_name'] != '' && $info['attribute_name'])
		{
			$where['g.attribute_name'] = $info['attribute_name'];
		}
        /*产品品牌*/
		if($info['brand_name'] != '' && $info['brand_name'])
		{
			$where['g.brand_name'] = $info['brand_name'];
		}
        /*产品子分类*/
		if($info['cat_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.cat_id'] = $info['cat_id'];
		}
        /*产品分类*/
		if($info['category_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.category_id'] = $info['category_id'];
		}
        /*产品颜色*/
		if($info['colour_name'] != '' && $info['colour_name'])
		{
			$where['g.colour_name'] = $info['colour_name'];
		}
        /*产品内存*/
		if($info['memory_name'] != '' && $info['memory_name'])
		{
			$where['g.memory_name'] = $info['memory_name'];
		}
        /*付款状态*/
		if($info['state'] != '' && $info['state'])
		{
			$where['o.state'] = $info['state']=='dai'?0:1;
		}
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['o.order_sn'] = ['like','%'.$info['sreach'].'%'];
		}
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['o.addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['o.addtime'][] = ['<',strtotime($info['end'])];
			}
			return $where;
		}
        /*上月、当前月*/
        if($info['shijian'] != '')
        {
            if($info['shijian'] == CommonModel::NUMBER_ZERO)
            {
                $where['o.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                $where['o.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
            }else{
                $where['o.addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                $where['o.addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
            }
        }
		return $where;
	}
    /**
    * 订单详情
    */
    public static function orderInfo($info)
    {
        $where['order_id'] = $info['oid'];
        $order = (new Order())->orderInfo($where);
        $OrderGoods = (new OrderGoods())->orderGoodsList($where);
        $OrderActivity = (new OrderActivity())->orderActivityInfo($where);
        return [$order,$OrderGoods,$OrderActivity];
    }
    /**
    * 退货、召回
    */
    public static function addAfterOrder($info)
    {
        /*获取订单商品数据*/
        $where['order_goods_id'] = $info['id'];
        $field = 'order_id,stock_id,goods_money,goods_id,imei,sn,number,buying_price';
        $orderGoodsInfo = (new OrderGoods())->orderGoodsInfo($where,$field);
        /*获取订单信息*/
        $where1['order_id'] = $orderGoodsInfo['order_id'];
        $orderInfo = (new Order())->orderInfo($where1);
        /*开启事物*/
        Db::startTrans();
        /*生成售后单*/
        $after['order_id'] = $orderInfo['order_id'];
        $after['shop_id'] = $orderInfo['shop_id'];
        $after['admin_id'] = Session::get('admin.admin_id');
        $after['username'] = $orderInfo['username'];
        $after['user_sn'] = $orderInfo['user_sn'];
        $after['nkname'] = $info['nkname'];
        $after['phone'] = $orderInfo['phone'];
        $after['after_goods'] = $info['id'];
        $after['reason'] = $info['reason'];
        $after['after_money'] = $orderGoodsInfo['goods_money'];
        $after['after_type'] = $info['after_type'];
        $time = $info['time']==0?time():strtotime($info['time']);
        $after['addtime'] = $time;
        if(!(new OrderAfter())->serOrderAfter($after))
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO')); 
        }
        $Stock  = new Stock();
        $getStockInfo = $Stock->getStockInfo(['stock_id'=>$orderGoodsInfo['stock_id']]);
        $getStockInfo['fid'] = $orderGoodsInfo['stock_id'];
        $getStockInfo['number'] = $orderGoodsInfo['number'];
        $getStockInfo['state'] = $info['after_type']==2?4:3;
        $getStockInfo['addtime'] = time();
        unset($getStockInfo['stock_id']);
        /*生成库存信息*/
        if(!$Stock->serStock($getStockInfo))
        {
            Db::rollback();
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        /*修改订单商品状态*/
        $isshow = $info['after_type']==2?2:1;
        if((new OrderGoods())->updateOrderGoods(['order_goods_id'=>$info['id']],['is_show'=>$isshow]) === false)
        {
           Db::rollback();
		   return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO')); 
        }
        Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 继续支付
    */
    public static function addMoney($info)
    {
        /*开启事物*/
        Db::startTrans();
        /*获取订单信息*/
        $order = new Order();
        $where['order_id'] = $info['id'];
        $orderdata = $order->orderInfo($where);
        /*判断应支付金额*/
        if(intval(strval($info['actual_money'] * 100)) > intval(strval($orderdata['stay_money'] * 100)))
        {
            return back(config('state.STATUS_CODE_THREE'),'支付金额大于待支付金额');
        }
        $data['stay_money'] = (intval(strval($orderdata['stay_money'] * 100)) - intval(strval($info['actual_money'] * 100)))/100;
        $data['actual_money'] = (intval(strval($orderdata['actual_money'] * 100)) + intval(strval($info['actual_money'] * 100)))/100;
        if(intval(strval($info['actual_money'] * 100)) == intval(strval($orderdata['stay_money'] * 100)))
         {
             $data['state'] = 1;
         }
        /*修改订单信息*/
        if($order->updateOrder($where,$data) === false)
        {
            Db::rollback();
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        /*添加支付信息*/
        $payLog['order_id'] = $info['id'];
        $payLog['pay_type'] = $info['pay_type'];
        $payLog['actual_money'] = $info['actual_money'];
        $payLog['nkname'] = Session::get('admin.nkname');
        $payLog['addtime'] = time();
        if(!(new OrderPayLog())->serPayLog($payLog))
        {
            Db::rollback();
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 支付记录
    */
    public function moneyLog($info)
    {
       $payLogList = (new OrderPayLog())->payLogList(['order_id'=>$info['id']]);
       $totl = 0;
       foreach($payLogList as $i=>$pay)
       {
          $payLogList[$i]['pay_type'] = self::payty($pay['pay_type']);
          $totl += intval(strval($pay['actual_money'] * 100));
       }
       $totl = $totl / 100;
       return [$payLogList,$totl];
    }
    private function payty($ty)
    {
        switch($ty)
        {
            case 0:return '现金支付';break;
            case 1:return '为手机支付';break;
            case 2:return '银行卡支付';break;
        }
    }
    /********************订单统计数据**********************/
    /**
    * 统计数据
    */
    private function order_count($where,$ty,$field = '')
    {
        if($ty == 'count')
        {
           return (new Order())->orderCount($where);
        }
        return (new Order())->orderSum($where,$field);
    }
    /**
    * 支付形式
    */
    private function payLogCount($ids,$ty)
    {
        $where['order_id'] = ['IN',$ids];
        $where['pay_type'] = $ty;
        return (new OrderPayLog())->payLogSum($where);
    }
}

